var companyCacheList = [];	// A List of companies that have been accessed.
var levelCacheMap = [];		// A Map keyed to company, with a list as the value.

function getCompanyList() {
	var localCache = companyCacheList.slice(0);
	if (localCache.length == 0) {
		DWREngine.setAsync(false);
		HierarchyProxy.findAllCompanies({timeout:1500,
		callback: function (data) {
			localCache = companyCacheList = data;
			
		}});
		DWREngine.setAsync(true);
			
	}
	return localCache;
	
}

function getCompany(companyId) {
	var companyList = getCompanyList();
	var company;
	
	for (var index = 0; index < companyList.length; index++) {
		if (companyList[index].id == companyId) {
			company = companyList[index];
			break;
			
		}
	
	}
	return company;
	
}

function getCompanyIndex(companyId) {
	var companyList = getCompanyList();
	var location = -1;
	
	
	for (var index = 0; index < companyList.length; index++) {
		if (companyList[index].id == companyId) {
			location = index;
			break;
			
		}
	} 
	return location;
	
}

function getLevelList(companyId) {
	var levelList = levelCacheMap[companyId];
	var localCache = levelCacheMap;
	if (!levelList) {
		DWREngine.setAsync(false);
		HierarchyProxy.findLevelsByCompany(companyId, {timeout:1500,
		callback:function (data) {
			localCache[companyId] = levelList = data;
			
		}});
		DWREngine.setAsync(true);
		
	} 
	return levelList;
	
}

function getCurrentLevel(companyId, levelValue) {
	var level;
	var levelList = getLevelList(companyId);
	
	for (var index = 0; index < levelList.length; index++) {
		if (levelList[index].value == levelValue) {
			level = levelList[index];
			break;
			
		}
	
	}
	return level;
	
}

function getLevel(companyId, levelId) {
	var level;
	var levelList = getLevelList(companyId);
	
	for (var index = 0; index < levelList.length; index++) {
		if (levelList[index].id == levelId) {
			level = levelList[index];
			break;
			
		}
	
	}
	return level;
	
	
}
function getLevelValue(companyId, levelId) {
	var level;
	if (!(level = getLevel(companyId, levelId))) {
		return false;
		
	}
	return level.value;
	
}

function getLowestLevel(companyId) {
	var level;
	var levelList = getLevelList(companyId);
	
	return levelList[levelList.length - 1];
	
}